package todolist.helpers;

import java.util.ArrayList;
import java.util.List;

import todolist.structures.User;


import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.util.Log;

public class userDataSource {

	// Database fields
	private SQLiteDatabase database;
	private dbHelper db;
	private String[] userColumns = { dbHelper.USER_COLUMN_ID,
			dbHelper.USER_COLUMN_UNAME, dbHelper.USER_COLUMN_PWORD };

	public userDataSource(Context context) {
		db = new dbHelper(context);
	}

	public void open() throws SQLException {
		database = db.getWritableDatabase();
	}

	public void close() {
		db.close();
	}

	public User createUser(String username, String password) {
		ContentValues values = new ContentValues();
		values.put(dbHelper.USER_COLUMN_UNAME, username);
		values.put(dbHelper.USER_COLUMN_PWORD, password);
		
		long insertId = database.insert(dbHelper.TABLE_USERS, null,
				values);
		// To show how to query
		Cursor cursor = database.query(dbHelper.TABLE_USERS,
				userColumns, dbHelper.USER_COLUMN_ID + " = " + insertId, null,
				null, null, null);
		cursor.moveToFirst();
		return cursorToUser(cursor);

	}

	public void deleteUser(User user) {
		long id = user.getId();
		System.out.println("User deleted with id: " + id);
		database.delete(dbHelper.TABLE_USERS, dbHelper.USER_COLUMN_ID
				+ " = " + id, null);
	}
	
	public List<User> getAllUsers() {
		List<User> users = new ArrayList<User>();
		Cursor cursor = database.query(dbHelper.TABLE_USERS,
				userColumns, null, null, null, null, null);
		cursor.moveToFirst();
		while (!cursor.isAfterLast()) {
			User user = cursorToUser(cursor);
			users.add(user);
			cursor.moveToNext();
		}
		// Make sure to close the cursor
		cursor.close();
		return users;
	}
	
	private User cursorToUser(Cursor cursor) {
		User user = new User();
		user.setId(cursor.getLong(0));
		user.setName(cursor.getString(1));
		user.setPassword(cursor.getString(2));
		return user;
	}

}